package com.liveneo.adapter.mobile.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.common.collect.Lists;
import com.liveneo.adapter.base.entity.PrpmDictDetail;
import com.liveneo.adapter.base.entity.PrpmSurveyUser;
import com.liveneo.adapter.base.entity.PrpmVideoConnection;
import com.liveneo.adapter.base.support.AdapterConstants;
import com.liveneo.adapter.base.support.BaseController;
import com.liveneo.adapter.base.support.LogUtils;
import com.liveneo.adapter.mobile.model.BaseResponse;
import com.liveneo.adapter.mobile.model.dto.MobileCodeDto;
import com.liveneo.adapter.mobile.model.request.VideoCaseRequest;
import com.liveneo.adapter.mobile.model.request.VideoConnectionRequest;
import com.liveneo.adapter.mobile.model.request.VideoVariableRequest;
import com.liveneo.adapter.mobile.model.response.QueueDataResponse;
import com.liveneo.adapter.mobile.model.response.VideoVariableResponse;
import com.liveneo.adapter.mobile.service.DictDetailService;
import com.liveneo.adapter.mobile.service.MobileVideoService;
import com.liveneo.adapter.mobile.service.PrpmSurveyUserService;
import com.liveneo.adapter.mobile.service.VideoConnectService;
import com.liveneo.adapter.mobile.support.MobileReturnCodeSupport;
import com.liveneo.adapter.mobile.util.UUIDUtils;
import com.liveneo.system.base.utils.EncryptUtil;
import com.liveneo.system.base.utils.JsonUtils;

/**
 * @author wangxx
 *
 */
@Controller
@RequestMapping("/mobile")
public class MobileVideoController extends BaseController {
    @Autowired
    private MobileVideoService    mobileVideoService;
    @Autowired
    private DictDetailService     dictService;
    @Autowired
    private VideoConnectService   videoConnectService;
    @Autowired
    private PrpmSurveyUserService prpmSurveyUserService;

    @RequestMapping("checkQueueData.action")
    @ResponseBody
    public String checkQueueData(@ModelAttribute(AdapterConstants.MOBILE_REQUEST_PARAM_NAME) String data) {
        String loguuid = UUIDUtils.getUUIDStr();
        String logTitle = "checkQueueData入参=" + loguuid;
        VideoCaseRequest request = JsonUtils.fromJsonWithBase64(logTitle, data, VideoCaseRequest.class);
        QueueDataResponse baseResponse = null;
        String result = "";
        try {
            String userCode = request.getUserCode();
            String caseNo = request.getCaseNo();
            String source = request.getProjectCode();
            if (userCode == null || "".equals(userCode)) {
                LogUtils.warn("传入的查勘员代码为空！请确认！");
                baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_ERR_PARAM, MobileReturnCodeSupport.SYS_CODE,
                        MobileReturnCodeSupport.CODE_PARAM_NO_USERCODE, QueueDataResponse.class);
            } else {
                Map<String, Object> map = mobileVideoService.getQueueDataByUserCode(userCode, caseNo, source);
                String forecast = null;
                String queuecnt = null;
                if (map != null) {
                    forecast = (String) map.get("forecast");
                    queuecnt = (String) map.get("queuecnt");
                }
                if (forecast == null || queuecnt == null) {
                    LogUtils.warn("获取的排队情况结果为空！请确认！");
                    baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_ERR_PARAM, MobileReturnCodeSupport.SYS_CODE,
                            MobileReturnCodeSupport.CODE_ERR_PARAM_NO_EXISTS, QueueDataResponse.class);
                } else {
                    baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_SUCCESS, MobileReturnCodeSupport.SYS_CODE, null,
                            QueueDataResponse.class);
                    baseResponse.setForecast(forecast);
                    baseResponse.setQueuecnt(queuecnt);
                }
            }
        } catch (Exception e) {
            LogUtils.error("获取案件排队情况，错误信息:", e);
            baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_ERR_PARAM, MobileReturnCodeSupport.SYS_CODE,
                    MobileReturnCodeSupport.CODE_ERR_PARAM_NO_EXISTS, QueueDataResponse.class);
        } finally {
            result = JsonUtils.toJson(baseResponse);
            // 日志记录响应json
            if (MobileReturnCodeSupport.CODE_SUCCESS.equals(baseResponse.getResultCode())) {
                LogUtils.info("返回结果【" + result + "】");
            } else {
                LogUtils.error("返回结果【" + result + "】");
            }
            result = EncryptUtil.encodeBase64(result);
        }
        return result;
    }

    @RequestMapping("addVideoConnect.action")
    @ResponseBody
    public String addVideoConnect(@ModelAttribute(AdapterConstants.MOBILE_REQUEST_PARAM_NAME) String data) {
        String loguuid = UUIDUtils.getUUIDStr();
        String logTitle = "addVideoConnect入参=" + loguuid;
        VideoConnectionRequest request = JsonUtils.fromJsonWithBase64(logTitle, data, VideoConnectionRequest.class);
        LogUtils.debug("维护采集端用户与视频控件id关系，传入参数：" + request);
        BaseResponse baseResponse = null;
        String result = "";
        try {
            String phoneNo = request.getPhoneNo();
            String terminalID = request.getTerminalID();
            if (phoneNo == null || terminalID == null) {
                baseResponse = MobileReturnCodeSupport.buildBaseReponse(MobileReturnCodeSupport.CODE_ERR_PARAM, MobileReturnCodeSupport.SYS_CODE,
                        MobileReturnCodeSupport.CODE_ERR_PARAM_NO_EXISTS);
            } else {
                mobileVideoService.addVideoConnection(phoneNo, terminalID);
                baseResponse = MobileReturnCodeSupport.buildBaseReponse(MobileReturnCodeSupport.CODE_SUCCESS, MobileReturnCodeSupport.SYS_CODE, null);
            }
        } catch (Exception e) {
            LogUtils.error("保存用户与视频控件id关系出错，错误信息:", e);
            baseResponse = MobileReturnCodeSupport.buildBaseReponse(MobileReturnCodeSupport.CODE_ERR_PARAM, MobileReturnCodeSupport.SYS_CODE,
                    MobileReturnCodeSupport.CODE_ERR_PARAM_NO_EXISTS);
        } finally {
            result = JsonUtils.toJson(baseResponse);
            // 日志记录响应json
            if (MobileReturnCodeSupport.CODE_SUCCESS.equals(baseResponse.getResultCode())) {
                LogUtils.info("返回结果【" + result + "】");
            } else {
                LogUtils.error("返回结果【" + result + "】");
            }
            result = EncryptUtil.encodeBase64(result);
        }
        return result;
    }

    @RequestMapping("getVideoVariable.action")
    @ResponseBody
    public String getVideoVariable(@ModelAttribute(AdapterConstants.MOBILE_REQUEST_PARAM_NAME) String data) {
        String loguuid = UUIDUtils.getUUIDStr();
        String logTitle = "getVideoVariable入参=" + loguuid;
        VideoVariableRequest request = JsonUtils.fromJsonWithBase64(logTitle, data, VideoVariableRequest.class);
        LogUtils.debug("获取视频变量，传入参数：" + request);
        VideoVariableResponse baseResponse = new VideoVariableResponse();
        String result = "";
        try {
            String codeType = request.getCodeType();
            List<PrpmDictDetail> dicts = dictService.queryDictsByDtUuid(codeType);
            List<MobileCodeDto> dtos = Lists.newArrayList();
            if (dicts != null && dicts.size() > 0) {
                for (PrpmDictDetail dict : dicts) {
                    MobileCodeDto dto = new MobileCodeDto();
                    dto.setCodeCode(dict.getDictCode());
                    dto.setCodeName(dict.getDictName());
                    dto.setCodeType(codeType);
                    if (dict.getModifyTime() != null) {
                        dto.setUpdateTime(DateUtils.formatDate(dict.getModifyTime()));
                    }
                    dto.setUuid(dict.getDictId());
                    dtos.add(dto);
                }
            }
            baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_SUCCESS, MobileReturnCodeSupport.SYS_CODE, null,
                    VideoVariableResponse.class);
            baseResponse.setMobileCodeDtoList(dtos);
        } catch (Exception e) {
            LogUtils.error("获取视频变量出错，错误信息:", e);
            baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_ERR_PARAM, MobileReturnCodeSupport.SYS_CODE,
                    MobileReturnCodeSupport.CODE_ERR_PARAM_NO_EXISTS, VideoVariableResponse.class);
        } finally {
            result = JsonUtils.toJson(baseResponse);
            // 日志记录响应json
            if (MobileReturnCodeSupport.CODE_SUCCESS.equals(baseResponse.getResultCode())) {
                LogUtils.info("返回结果【" + result + "】");
            } else {
                LogUtils.error("返回结果【" + result + "】");
            }
            result = EncryptUtil.encodeBase64(result);
        }
        return result;
    }

    /**
     * 维护采集端用户与视频控件id关系
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping("protectVideoConnect.action")
    @ResponseBody
    public String protectVideoConnect(@ModelAttribute(AdapterConstants.MOBILE_REQUEST_PARAM_NAME) String data) {
        String loguuid = UUIDUtils.getUUIDStr();
        String logTitle = "protectVideoConnect入参=" + loguuid;
        VideoVariableRequest request = JsonUtils.fromJsonWithBase64(logTitle, data, VideoVariableRequest.class);
        VideoVariableResponse baseResponse = null;
        String result = "";
        try {
            // String phoneNo = request.getPhoneNo();
            String userCode = request.getUserCode();
            String terminalID = request.getTerminalID();
            PrpmVideoConnection prpmVideoConnection = videoConnectService.getVideoConnectByphoneNo(userCode);
            if (prpmVideoConnection != null && !"".equals(prpmVideoConnection)) {
                prpmVideoConnection.setTerminalId(terminalID);
                prpmVideoConnection.setModifyTime(new Date());
                videoConnectService.updateByUuid(prpmVideoConnection);
            } else {
                PrpmSurveyUser prpmSurveyUser = prpmSurveyUserService.findUserByUserCode(userCode);
                PrpmVideoConnection videoConnect = new PrpmVideoConnection();
                videoConnect.setVideoConnectionId(UUIDUtils.getUUIDStr());
                videoConnect.setMobile(userCode);
                videoConnect.setTerminalId(terminalID);
                if (prpmSurveyUser != null && !"".equals(prpmSurveyUser)) videoConnect.setUserCode(prpmSurveyUser.getSurveyUserCode());
                videoConnect.setModifyTime(new Date());
                videoConnectService.insert(videoConnect);
            }
            baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_SUCCESS, MobileReturnCodeSupport.SYS_CODE, null,
                    VideoVariableResponse.class);
        } catch (Exception e) {
            LogUtils.error("维护采集端用户与视频控件id关系出错，错误信息:", e);
            baseResponse = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_FAIL, MobileReturnCodeSupport.SYS_CODE, null,
                    VideoVariableResponse.class);
        } finally {
            result = JsonUtils.toJson(baseResponse);
            // 日志记录响应json
            if (MobileReturnCodeSupport.CODE_SUCCESS.equals(baseResponse.getResultCode())) {
                LogUtils.info("返回结果【" + result + "】");
            } else {
                LogUtils.error("返回结果【" + result + "】");
            }
            result = EncryptUtil.encodeBase64(result);
        }
        return result;
    }
}
